package com.kqb.service.impl;

import com.kqb.common.domain.AjaxResult;
import com.kqb.common.domain.ErrorResult;
import com.kqb.common.utils.DateUtils;
import com.kqb.common.utils.StringUtils;
import com.kqb.mapper.ErpProductInquirySheetMapper;
import com.kqb.mapper.ErpProductInquirySheetProductMapper;
import com.kqb.pojo.ErpProductInquirySheet;
import com.kqb.service.IErpProductInquiryService;
import com.kqb.utils.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author 杉果树皮
 * @date 2025/3/4 19:42
 * @description: '
 */
@Service
public class ErpProductInquiryServiceImpl implements IErpProductInquiryService {
    @Autowired
    private ErpProductInquirySheetMapper erpProductInquirySheetMapper;
    @Autowired
    private ErpProductInquirySheetProductMapper erpProductInquirySheetProductMapper;
    private String maxSn;

    @Transactional
    @Override
    public AjaxResult save(ErpProductInquirySheet erpProductInquirySheet) {
        Map currentUser = ThreadLocalUtils.getThreadLocalUtils().getCurrentUser();
        int id = (int) currentUser.get("id");
        String userInfo = (String) currentUser.get("userInfo");
        String role = ((String[]) currentUser.get("roles"))[0];
        //判断角色销售可以创建询价单
        if ("sale".equals(role)) {
            erpProductInquirySheet.setSellerId(id);
            erpProductInquirySheet.setSellerName(userInfo);
        }
        String sn = generateMaxSn();
        erpProductInquirySheet.setSn(sn);
        int save = erpProductInquirySheetMapper.save(erpProductInquirySheet);
        ErrorResult.business(save, "供应商询价", "询价单添加失败");
        if (StringUtils.isNotNull(erpProductInquirySheet.getErpProductInquirySheetProducts()) && erpProductInquirySheet.getErpProductInquirySheetProducts().size() > 0) {
            erpProductInquirySheetProductMapper.save(erpProductInquirySheet.getId(), erpProductInquirySheet.getErpProductInquirySheetProducts());
            ErrorResult.business(save, "供应商询价", "询价产品添加失败");
        }
        return AjaxResult.success("添加询价单成功");
    }

    public String generateMaxSn() {
        //获取当前ym 20250304 -> 2503
        String ym = DateUtils.getSysDateYM();
        //如果内存中不存在maxSn
        if (StringUtils.isNull(maxSn)) {
            maxSn = erpProductInquirySheetMapper.getMaxSn();
            if (StringUtils.isNull(maxSn))
                return maxSn = "GYXJ" + ym + "0001";
            //GYXJ25030001
        }
        //内存中存在数据库中一定存在
        if (!ym.equals(maxSn.substring(4, 8)))
            return maxSn = "GYXJ" + ym + "0001";
        String prefix = maxSn.substring(0, 8);
        int suffix = Integer.parseInt(maxSn.substring(8));
        suffix++;
        return maxSn = prefix + String.format("%04d", suffix);
    }
}
